import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wan_android/application.dart';
import 'package:flutter_wan_android/arch/net/http_manager.dart';
import 'package:flutter_wan_android/arch/net/result_data.dart';
import 'package:flutter_wan_android/arch/ui/toast.dart';
import 'package:flutter_wan_android/arch/util/sputil.dart';
import 'package:flutter_wan_android/common/api.dart';
import 'package:flutter_wan_android/event/event.dart';
import 'package:flutter_wan_android/event/event_bus.dart';
import 'package:flutter_wan_android/model/user_info.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/routes/route_util.dart';
import 'package:flutter_wan_android/widget/wan_appbar.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  String _user = "";

  String _pwd = "";

  late TextEditingController _userController;
  late TextEditingController _pwdController;

  @override
  void initState() {

    Application.isLoginPage = true;
    Application.hasLogin = false;

    _userController = TextEditingController();
    _pwdController = TextEditingController();

    _initData();
    super.initState();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

  @override
  void dispose(){
    Application.isLoginPage = false;
    super.dispose();
  }

  _initData() {
    SpUtil.getString("userName").then((value) {
      setState(() {
        _user = value;
        _userController.text = _user;
      });
    });

    SpUtil.getString("pwd").then((value) {
      setState(() {
        _pwd = value;
        _pwdController.text = _pwd;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: WanAppbar(
          context,
          titleStr: "登录",
          backgroundColor: WColor.white,
          iconTheme: IconThemeData.fallback(),
        ),
        body: Container(
          padding: EdgeInsets.only(left: 40, right: 40, top: 10),
          color: WColor.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "登录",
                style: TextStyle(
                  color: WColor.blue1,
                  fontSize: 22,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Padding(padding: EdgeInsets.only(top: 50)),
              TextField(
                // autofocus: true,
                controller: _userController,
                decoration: InputDecoration(
                    labelText: "用户名",
                    hintText: "请输入用户名",
                    prefixIcon: Icon(Icons.person),
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 8, vertical: 10),
                    border: OutlineInputBorder()),
                onChanged: (value) {
                  _user = value;
                },
              ),
              Padding(padding: EdgeInsets.only(top: 30)),
              TextField(
                controller: _pwdController,
                decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  prefixIcon: Icon(Icons.lock),
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 8, vertical: 15),
                  border: OutlineInputBorder(),
                ),
                obscureText: true,
                onChanged: (value) {
                  _pwd = value;
                },
              ),
              Padding(padding: EdgeInsets.only(top: 50)),
              SizedBox(
                width: double.infinity,
                height: 44,
                child: FlatButton(
                  color: WColor.blue1,
                  // highlightColor: Colors.blue[700],
                  colorBrightness: Brightness.dark,
                  child: Text(
                    "登录",
                    style: TextStyle(fontSize: 18),
                  ),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(40.0)),
                  onPressed: _login,
                ),
              )
            ],
          ),
        ));
  }

  /// 登录
  _login() async {
    if (_user.isEmpty) {
      ToastUtil.show("请输入用户名");
      return;
    }

    if (_pwd.isEmpty || _user.isEmpty) {
      ToastUtil.show("请输入密码");
      return;
    }

    ResultData result = await HttpManager.instance().post(
      Api.LOGIN,
      params: {"username": _user, "password": _pwd},
    );

    if (result.success) {
      ToastUtil.show("登录成功");
      SpUtil.put("userName", _user);
      SpUtil.put("pwd", _pwd);
      Application.hasLogin = true;
      Application.userInfo = UserInfo.fromJson(result.data);

      // 发送通知刷新页面
      EventBusUtil.getInstance().fire(WEvent.EVENT_LOGIN);
      RouteUtil.pop(context);
    } else {
      ToastUtil.show(result.msg);
    }
  }
}
